import 'package:app_core/app_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'dart:convert';

import 'package:yh_core_flutter_project/project/common/constant/colors.dart';

/// YHWebViewPage - 功能完整的WebView页面
/// 支持：加载进度、错误处理、JavaScript交互、导航控制、刷新等功能
class YHWebViewPage extends StatefulWidget {
  final String? initialUrl;
  final String? title;
  final bool showProgressBar;
  final bool showRefreshButton;
  final bool showBackForwardButtons;
  final bool enableJavaScript;
  final bool enableDomStorage;
  final Map<String, String>? headers;
  final Function(InAppWebViewController)? onWebViewCreated;
  final Function(String)? onUrlChanged;
  final Function(int)? onProgressChanged;
  final Function(String)? onError;
  final Function()? onLoadComplete;
  // 通用回调：把“业务”上抛给外层
  final void Function(String message)? onToastRequested;
  final void Function(String route, dynamic params)? onNavigateRequested;
  final Future<dynamic> Function(String method, dynamic params)? onCallNative;

  const YHWebViewPage({
    super.key,
    this.initialUrl,
    this.title,
    this.showProgressBar = true,
    this.showRefreshButton = true,
    this.showBackForwardButtons = true,
    this.enableJavaScript = true,
    this.enableDomStorage = true,
    this.headers,
    this.onWebViewCreated,
    this.onUrlChanged,
    this.onProgressChanged,
    this.onError,
    this.onLoadComplete,
    this.onToastRequested,
    this.onNavigateRequested,
    this.onCallNative,
  });

  @override
  State<YHWebViewPage> createState() => _YHWebViewPageState();
}

class _YHWebViewPageState extends State<YHWebViewPage> {
  InAppWebViewController? _webViewController;
  String _currentUrl = '';
  String _currentTitle = '';
  int _progress = 0;
  bool _isLoading = false;
  bool _hasError = false;
  String _errorMessage = '';
  bool _canGoBack = false;
  bool _canGoForward = false;
  // 内联通用数据容器
  Map<String, dynamic> _pageData = {};
  
  // iOS 平台错误防护
  bool _isDisposed = false;

  @override
  void initState() {
    super.initState();
    _currentUrl = widget.initialUrl ?? 'https://www.baidu.com';
    _pageData = {
      'theme': 'light',
      'language': 'zh',
      'timestamp': DateTime.now().millisecondsSinceEpoch,
    };
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(appBar: _buildAppBar(), body: Column(children: [Expanded(child: _buildBody()), _buildDemoPanel()]));
  }

  /// 构建AppBar
  PreferredSizeWidget _buildAppBar() {
    return MyAppBar(
      widget.title ?? (_currentTitle.isNotEmpty ? _currentTitle : 'WebView'),
      actions: _buildAppBarActions(),
      bottom: widget.showProgressBar ? _buildProgressBar() : null,
    );
    // return AppBar(
    //   title: Text(widget.title ?? (_currentTitle.isNotEmpty ? _currentTitle : 'WebView'), style: TextStyle(fontSize: 18)),
    //   leading: IconButton(icon: Icon(Icons.arrow_back), onPressed: () => Navigator.of(context).pop()),
    //   actions: _buildAppBarActions(),
    //   bottom: widget.showProgressBar ? _buildProgressBar() : null,
    // );
  }

  /// 构建AppBar操作按钮
  List<Widget> _buildAppBarActions() {
    final actions = <Widget>[];

    if (widget.showBackForwardButtons) {
      actions.addAll([
        IconButton(icon: Icon(Icons.arrow_back_ios, size: 20), onPressed: _canGoBack ? _goBack : null, tooltip: '后退'),
        IconButton(icon: Icon(Icons.arrow_forward_ios, size: 20), onPressed: _canGoForward ? _goForward : null, tooltip: '前进'),
      ]);
    }

    if (widget.showRefreshButton) {
      actions.add(
        IconButton(icon: Icon(_isLoading ? Icons.stop : Icons.refresh), onPressed: _isLoading ? _stopLoading : _refresh, tooltip: _isLoading ? '停止' : '刷新'),
      );
    }

    // actions.add(
    //   IconButton(icon: Icon(_isLoading ? Icons.stop : Icons.refresh), onPressed: _isLoading ? _stopLoading : _refresh, tooltip: _isLoading ? '停止' : '刷新'),
    // );

    // actions.add(
    //   PopupMenuButton<String>(
    //     icon: Icon(Icons.more_vert),
    //     onSelected: _handleMenuAction,
    //     itemBuilder:
    //         (context) => [
    //           PopupMenuItem(value: 'copy_url', child: Row(children: [Icon(Icons.copy, size: 18), SizedBox(width: 8), Text('复制链接')])),
    //           PopupMenuItem(value: 'open_browser', child: Row(children: [Icon(Icons.open_in_browser, size: 18), SizedBox(width: 8), Text('在浏览器中打开')])),
    //           PopupMenuItem(value: 'share', child: Row(children: [Icon(Icons.share, size: 18), SizedBox(width: 8), Text('分享')])),
    //         ],
    //   ),
    // );
    return actions;
  }

  /// 构建进度条
  PreferredSizeWidget _buildProgressBar() {
    return PreferredSize(
      preferredSize: Size.fromHeight(1),
      child:
          _progress > 0 && _progress < 100
              ? LinearProgressIndicator(
                value: _progress / 100,
                backgroundColor: AppColor.lineColor,
                valueColor: AlwaysStoppedAnimation<Color>(Theme.of(context).primaryColor),
              )
              : SizedBox.shrink(),
    );
  }

  /// 构建页面主体
  Widget _buildBody() {
    // if (_hasError) {
    //   return _buildErrorView();
    // }

    return InAppWebView(
      initialUrlRequest: URLRequest(url: WebUri(_currentUrl), headers: widget.headers),
      onWebViewCreated: _onWebViewCreated,
      onLoadStart: _onLoadStart,
      onLoadStop: _onLoadStop,
      onReceivedError: _onReceivedError,
      onReceivedHttpError: _onReceivedHttpError,
      onProgressChanged: _onProgressChanged,
      onTitleChanged: _onTitleChanged,
      onConsoleMessage: _onConsoleMessage,
    );
  }

  /// 演示面板：展示 Flutter 与 H5 双向通信
  Widget _buildDemoPanel() {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(color: Colors.grey.shade50, border: Border(top: BorderSide(color: Colors.grey.shade300))),
      padding: EdgeInsets.fromLTRB(12, 8, 12, 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.link, size: 16, color: Colors.grey.shade700),
              SizedBox(width: 6),
              Text('双向通信演示', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: Colors.grey.shade800)),
              Spacer(),
              TextButton(onPressed: _injectDemoScriptIntoPage, child: Text('在H5注入演示按钮')),
            ],
          ),
          SizedBox(height: 6),
          Wrap(
            spacing: 8,
            runSpacing: 6,
            children: [
              _demoBtn('Flutter→H5: 发送数据', _demoSendDataToH5),
              _demoBtn('Flutter→H5: 设置pageData', _demoSetPageData),
              _demoBtn('H5→Flutter: toast', _demoH5CallToast),
              _demoBtn('H5→Flutter: navigate', _demoH5Navigate),
              _demoBtn('H5→Flutter: emit', _demoH5Emit),
            ],
          ),
          SizedBox(height: 6),
          _buildPageDataView(),
        ],
      ),
    );
  }

  Widget _demoBtn(String text, VoidCallback onPressed) {
    return OutlinedButton(onPressed: onPressed, child: Text(text, style: TextStyle(fontSize: 12)));
  }

  Widget _buildPageDataView() {
    if (_pageData.isEmpty) {
      return Text('pageData: {}', style: TextStyle(fontSize: 12, color: Colors.grey.shade700));
    }
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(8),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(6), border: Border.all(color: Colors.grey.shade300)),
      child: Text('pageData: ' + jsonEncode(_pageData), style: TextStyle(fontSize: 12, color: Colors.grey.shade800)),
    );
  }

  /// 构建错误视图
  Widget _buildErrorView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.error_outline, size: 64, color: Colors.red[300]),
          SizedBox(height: 16),
          Text('加载失败', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
          SizedBox(height: 8),
          Text(_errorMessage, style: TextStyle(fontSize: 14, color: Colors.grey[600]), textAlign: TextAlign.center),
          SizedBox(height: 24),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [ElevatedButton(onPressed: _retry, child: Text('重试')), SizedBox(width: 16), ElevatedButton(onPressed: _goBack, child: Text('返回'))],
          ),
        ],
      ),
    );
  }

  /// WebView创建完成
  void _onWebViewCreated(InAppWebViewController controller) {
    if (_isDisposed) return;
    
    _webViewController = controller;
    
    try {
      _registerJavaScriptHandlers();
      _injectBridgeAndInitData();
      widget.onWebViewCreated?.call(controller);
    } catch (e) {
      if (kDebugMode) {
        print('WebView created error: $e');
      }
    }
  }

  /// 开始加载
  void _onLoadStart(InAppWebViewController controller, Uri? url) {
    if (_isDisposed) return;
    
    setState(() {
      _isLoading = true;
      _hasError = false;
      _errorMessage = '';
      _progress = 0;
    });

    if (url != null) {
      _currentUrl = url.toString();
      widget.onUrlChanged?.call(_currentUrl);
    }
  }

  /// 加载完成
  void _onLoadStop(InAppWebViewController controller, Uri? url) {
    if (_isDisposed) return;
    
    setState(() {
      _isLoading = false;
      _progress = 100;
    });

    _updateNavigationState();
    widget.onLoadComplete?.call();
  }

  /// 加载错误
  void _onReceivedError(InAppWebViewController controller, WebResourceRequest request, WebResourceError error) {
    if (_isDisposed) return;
    
    /// 忽略 iOS 上常见的取消错误（NSURLErrorCancelled = -999），避免误显示错误页
    if (error.type == WebResourceErrorType.CANCELLED || 
        error.description.toLowerCase().contains('cancelled') || 
        error.description.contains('-999')) {
      return;
    }

    setState(() {
      _isLoading = false;
      _hasError = true;
      _errorMessage = '加载失败: ${error.description} (错误类型: ${error.type})';
    });

    widget.onError?.call(_errorMessage);
  }

  /// HTTP错误
  void _onReceivedHttpError(InAppWebViewController controller, WebResourceRequest request, WebResourceResponse response) {
    if (_isDisposed) return;
    
    setState(() {
      _isLoading = false;
      _hasError = true;
      _errorMessage = 'HTTP错误: ${response.statusCode} - ${response.reasonPhrase ?? '未知错误'}';
    });

    widget.onError?.call(_errorMessage);
  }

  /// 进度变化
  void _onProgressChanged(InAppWebViewController controller, int progress) {
    if (_isDisposed) return;
    
    setState(() {
      _progress = progress;
    });

    widget.onProgressChanged?.call(progress);
  }

  /// 标题变化
  void _onTitleChanged(InAppWebViewController controller, String? title) {
    if (_isDisposed) return;
    
    if (title != null && title.isNotEmpty) {
      setState(() {
        _currentTitle = title;
      });
    }
  }

  /// MARK: - JS Bridge（通用）
  void _registerJavaScriptHandlers() {
    if (_webViewController == null) return;

    /// 读取/设置页面数据
    _webViewController!.addJavaScriptHandler(handlerName: 'native.getPageData', callback: (args) => _pageData);
    _webViewController!.addJavaScriptHandler(
      handlerName: 'native.setPageData',
      callback: (args) {
        if (args.isNotEmpty && args.first is Map<String, dynamic>) {
          _pageData.addAll(args.first as Map<String, dynamic>);
        }
        return null;
      },
    );

    /// Toast
    _webViewController!.addJavaScriptHandler(
      handlerName: 'native.toast',
      callback: (args) {
        final message = args.isNotEmpty ? args.first?.toString() ?? '' : '';
        if (message.isNotEmpty) widget.onToastRequested?.call(message);
        return null;
      },
    );

    /// 导航
    _webViewController!.addJavaScriptHandler(
      handlerName: 'native.navigate',
      callback: (args) {
        final route = args.isNotEmpty ? args.first?.toString() ?? '' : '';
        final params = args.length > 1 ? args[1] : null;
        if (route.isNotEmpty) widget.onNavigateRequested?.call(route, params);
        return null;
      },
    );

    /// 通用原生调用
    _webViewController!.addJavaScriptHandler(
      handlerName: 'native.call',
      callback: (args) async {
        final method = args.isNotEmpty ? args.first?.toString() ?? '' : '';
        final params = args.length > 1 ? args[1] : null;
        if (widget.onCallNative != null && method.isNotEmpty) {
          return await widget.onCallNative!(method, params);
        }
        return {'success': false, 'message': 'No native handler for ' + method};
      },
    );
  }

  Future<void> _injectBridgeAndInitData() async {
    if (_webViewController == null) return;
    try {
      await _webViewController!.evaluateJavascript(
        source:
            'window.flutterData = { page: ' +
            jsonEncode(_pageData) +
            ' };'
                'window.FlutterBridge = window.FlutterBridge || {\n'
                '  receiveData: function(d){ if(window.onFlutterDataReceived) window.onFlutterDataReceived(d); },\n'
                '  on: function(e, cb){ if(!window.flutterEvents) window.flutterEvents = {}; (window.flutterEvents[e] ||= []).push(cb); },\n'
                '  emit: function(e, d){ if(window.flutterEvents && window.flutterEvents[e]) window.flutterEvents[e].forEach(function(cb){ cb(d); }); }\n'
                '};',
      );
    } catch (_) {}
  }

  Future<void> sendDataToWebView(Map<String, dynamic> data) async {
    if (_webViewController == null) return;
    await _webViewController!.evaluateJavascript(source: 'window.FlutterBridge && window.FlutterBridge.receiveData(' + jsonEncode(data) + ');');
  }

  /// 控制台消息
  void _onConsoleMessage(InAppWebViewController controller, ConsoleMessage consoleMessage) {
    if (_isDisposed) return;
    
    if (kDebugMode) {
      print('WebView Console: ${consoleMessage.message}');
    }
  }

  /// 后退
  void _goBack() {
    if (_canGoBack) {
      _webViewController?.goBack();
    }
  }

  /// 前进
  void _goForward() {
    if (_canGoForward) {
      _webViewController?.goForward();
    }
  }

  /// 刷新
  void _refresh() {
    _webViewController?.reload();
  }

  /// 停止加载
  void _stopLoading() {
    _webViewController?.stopLoading();
  }

  /// 重试
  void _retry() {
    setState(() {
      _hasError = false;
      _errorMessage = '';
    });
    _webViewController?.reload();
  }

  /// 更新导航状态
  void _updateNavigationState() {
    if (_webViewController != null) {
      _webViewController!.canGoBack().then((canGoBack) {
        if (mounted) {
          setState(() {
            _canGoBack = canGoBack;
          });
        }
      });

      _webViewController!.canGoForward().then((canGoForward) {
        if (mounted) {
          setState(() {
            _canGoForward = canGoForward;
          });
        }
      });
    }
  }

  /// 处理菜单操作
  void _handleMenuAction(String action) {
    switch (action) {
      case 'copy_url':
        _copyUrl();
        break;
      case 'open_browser':
        _openInBrowser();
        break;
      case 'share':
        _shareUrl();
        break;
    }
  }

  /// 复制URL
  void _copyUrl() {
    /// 这里可以集成剪贴板功能
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('链接已复制: $_currentUrl')));
  }

  /// 在浏览器中打开
  void _openInBrowser() {
    /// 这里可以集成url_launcher包来打开外部浏览器
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('请在浏览器中打开: $_currentUrl')));
  }

  /// 分享URL
  void _shareUrl() {
    /// 这里可以集成分享功能
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('分享链接: $_currentUrl')));
  }

  // MARK: - Demo actions
  void _demoSendDataToH5() {
    sendDataToWebView({'time': DateTime.now().toIso8601String(), 'from': 'Flutter'});
  }

  void _demoSetPageData() {
    _pageData['lastSetAt'] = DateTime.now().millisecondsSinceEpoch;
    _pageData['counter'] = (_pageData['counter'] ?? 0) + 1;
    _injectBridgeAndInitData();
    setState(() {});
  }

  void _demoH5CallToast() {
    if (_webViewController == null) return;
    _webViewController!.evaluateJavascript(source: "window.flutter_inappwebview && window.flutter_inappwebview.callHandler('native.toast','来自H5的问候')");
  }

  void _demoH5Navigate() {
    if (_webViewController == null) return;
    _webViewController!.evaluateJavascript(
      source: "window.flutter_inappwebview && window.flutter_inappwebview.callHandler('native.navigate','/mine',{from:'web-demo'})",
    );
  }

  void _demoH5Emit() {
    if (_webViewController == null) return;
    _webViewController!.evaluateJavascript(
      source: "window.flutter_inappwebview && window.flutter_inappwebview.callHandler('native.emit','eventFromH5',{foo:123})",
    );
  }

  // 在H5页面注入可视化演示按钮（便于联调）
  void _injectDemoScriptIntoPage() {
    if (_webViewController == null) return;
    _webViewController!.evaluateJavascript(
      source: '''
      (function(){
        if (document.getElementById('flutter-demo-bar')) return;
        var bar = document.createElement('div');
        bar.id = 'flutter-demo-bar';
        bar.style.cssText = 'position:fixed;left:10px;bottom:10px;z-index:999999;padding:8px;background:#fff;border:1px solid #ddd;border-radius:6px;font-size:12px;';
        function btn(text, cb){ var b=document.createElement('button'); b.innerText=text; b.style.marginRight='6px'; b.onclick=cb; return b; }
        bar.appendChild(btn('toast', function(){ window.flutter_inappwebview && window.flutter_inappwebview.callHandler('native.toast','H5->Flutter toast'); }));
        bar.appendChild(btn('navigate', function(){ window.flutter_inappwebview && window.flutter_inappwebview.callHandler('native.navigate','/mine',{from:'demo-bar'}); }));
        bar.appendChild(btn('emit', function(){ window.flutter_inappwebview && window.flutter_inappwebview.callHandler('native.emit','event',{demo:true}); }));
        document.body.appendChild(bar);
      })();
    ''',
    );
  }

  @override
  void dispose() {
    _isDisposed = true;
    /// 安全地销毁 WebView
    if (_webViewController != null) {
      try {
        _webViewController!.dispose();
        _webViewController = null;
      } catch (e) {
        print('WebView dispose error: $e');
      }
    }
    super.dispose();
  }
}
